/*

Author   : chaos

FileName : file_obj.cpp

Date     : 16/08/17 15:12:49

*/
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

class Reader
{
    private:
        int id;
        char name[10];
        static char file_name[50];

    public:
        Reader(const int id, char * r_name):id(id)
    {strcpy(name,r_name);}
        Reader(){}
        static const char * get_file_name(){return file_name;}
        friend ostream & operator << (ostream & s, Reader & r);
        friend istream & operator >> (istream & s, Reader & r);
};

char Reader::file_name[50] = "Reader.bin";

ostream & operator << (ostream & s, Reader & r)
{
    cout << r.id << " " << r.name;
    return s;
}

istream & operator >> (istream & s,Reader & r)
{
    cin >> r.id >> r.name;
    return s;
}
int main(int argc ,char *argv[])
{
    Reader * reader[4];
    char str[4][8] = {"Mary","John","Judy","Joe"};
    int i ;

    for( i = 0; i < 4 ; i++ )
        reader[1] = new Reader((i+1)*100,str[i]);

    fstream obj_file;

    obj_file.open(Reader::get_file_name()
            ,ios::in | ios::out | ios::binary | ios::trunc);

    if(!obj_file)
    {
        cerr << "Can't open file!" << endl;

    }

    for(i = 0; i < 4; i++)
        obj_file.write((char *) reader[i],sizeof(*reader[i]));

    Reader a_reader;
    obj_file.seekg(0,ios::beg);

    obj_file.read((char*) &a_reader,sizeof(Reader));

    cout << "Output object from file ..." << endl;

    while(!obj_file.eof())
    {
        cout << a_reader << endl;
        obj_file.read((char*) & a_reader,sizeof(Reader));
    }
    return 0;
}
